<template>
  <!--主div节点 -->
  <div class="app-container">
     <!--主表单 ref的作用获取对该表单组件的引用的属性 inline：行内元素自动为一行
     v-show的作用是改变元素css的display属性 是否隐藏 不去除dom元素
     clearable:是否可清空 默认false
     @keyup.enter.native 加了native作用覆盖原有按回车默认提交表单的行为
     -->
     <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px" >
       <el-form-item label="学生名称" prop="studentName">
         <el-input
             v-model="queryParams.studentName"
             placeholder="请输入学生名称"
             clearable
             size="small"
             @keyup.enter.native="handleQuery"
         />
       </el-form-item>
       <el-form-item label="年龄" prop="studentAge">
         <el-input
             v-model="queryParams.studentAge"
             placeholder="请输入年龄"
             clearable
             size="small"
             @keyup.enter.native = "handleQuery"
         />
       </el-form-item>
       <el-form-item label="爱好" prop="studentHobby">
         <el-input
           v-model="queryParams.studentHobby"
           placeholder="请输入爱好"
           clearable
           size="small"
           @keyup.enter.native = "handleQuery"
         />
       </el-form-item>
       <el-form-item label="性别" prop="studentSex">
         <el-select v-model="queryParams.studentSex" placeholder="请选择性别" clearable size="small">
           <el-option v-for="dict in dict.type.sys_user_sex"
                      :key = "dict.value"
                      :value = "dict.value"
                      :label = "dict.label"
           ></el-option>
         </el-select>
       </el-form-item>
       <el-form-item label="状态" prop="studentStatus">
         <el-select v-model="queryParams.studentStatus" placeholder="请选择状态" clearable size="small">
           <el-option v-for="dict in dict.type.sys_normal_disable"
                      :key = "dict.value"
                      :value = "dict.value"
                      :label = "dict.label"
           >
           </el-option>
         </el-select>
       </el-form-item>
       <el-form-item label="生日" prop="studentBirthday">
         <el-date-picker clearable size="small"
           v-model="queryParams.studentBirthday"
           type="date"
           value-format="yyyy-MM-dd"
           placeholder="选择生日">
         </el-date-picker>
       </el-form-item>
       <el-form-item>
         <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
         <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
       </el-form-item>
     </el-form>
     <!-- :gutter参数设置行内间的间距 :span 列所占据栅格数
         plain是否朴素按钮-->
     <el-row :gutter="10" class="mb8">
       <el-col :span="1.5">
         <el-button
           type="primary"
           plain
           icon="el-icon-plus"
           size="mini"
           @click = "handleAdd"
           v-hasPermi="['system:student:add']"
         >新增</el-button>
       </el-col>
       <el-col :span="1.5">
         <el-button
           type="success"
           plain
           icon="el-icon-edit"
           size="mini"
           :disabled="single"
           @click="handleUpdate"
           v-hasPermi="['system:student:edit']"
         >修改</el-button>
       </el-col>
       <el-col :span="1.5">
         <el-button
           type="danger"
           plain
           icon="el-icon-delete"
           size="mini"
           :disabled = "multiple"
           @click="handleDelete"
           v-hasPermi="['system:student:remove']"
         >删除</el-button>
       </el-col>
       <el-col :span="1.5">
         <el-button
           type="info"
           plain
           icon="el-icon-upload2"
           size="mini"
           @click="handleImport"
           v-hasPermi="['system:student:import']"
         >导入</el-button>
       </el-col>
       <el-col :span="1.5">
         <el-button
           type="warning"
           plain
           icon="el-icon-download"
           size="mini"
           @click="handleExport"
           v-hasPermi="['system:student:export']"
         >导出</el-button>
       </el-col>
       <!--this.$emit 用于触发一个组件实例上的事件 一般用于触发组件方法
          right-toolbar: 显示隐藏搜索条件 @表示触发方法-->
       <right-toolbar :show-search.sync="showSearch" @queryTable = "getList"></right-toolbar>
     </el-row>
     <!--关于table的一些
        @selection-change：多选框被选中时触发 用于获取行数据  -->
     <el-table v-loading="loading" :data="studentList" @selection-change = "handleSelectionChange">
       <el-table-column type="selection" width="55" align="center"/>
       <el-table-column label="编号" align="center" prop="studentId"/>
       <el-table-column label="学生名称" align="center" prop="studentName"/>
       <el-table-column label="年龄" align="center" prop="studentAge"/>
       <el-table-column label="爱好" align="center" prop="studentHobby"/>
<!--       <el-table-column label="性别" align="center" prop="studentSex"/>-->
       <el-table-column label="状态" align="center" prop="studentStatus">
         <!--根据字典来显示内容 -->
         <template v-slot="scope">
           <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.studentStatus"/>
         </template>
       </el-table-column>
       <el-table-column label="生日" align="center" prop="studentBirthday" width="180">
         <!--获取行数据 -->
         <template v-slot="scope">
           <span>{{ parseTime(scope.row.studentBirthday,'{y}-{m}-{d}') }}</span>
         </template>
       </el-table-column>
       <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
         <template v-slot="scope">
           <el-button
             size="mini"
             type="text"
             icon="el-icon-edit"
             @click="handleUpdate(scope.row)"
             v-hasPermi="['system:student:edit']"
           >修改</el-button>
           <el-button
             size="mini"
             type="text"
             icon="el-icon-delete"
             @click="handleDelete(scope.row)"
             v-hasPermi="['system:student:remove']"
           >删除</el-button>
         </template>
       </el-table-column>
     </el-table>
     <!-- 分页组件-->
     <pagination
       v-show="total>0"
       :total="total"
       :page.sync="queryParams.pageNum"
       :limit.sync="queryParams.pageSize"
       @pagination = "getList"
     />

    <!-- 添加或修改学生信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学生名称" prop="studentName">
          <el-input v-model="form.studentName" placeholder="请输入学生名称"/>
        </el-form-item>
        <el-form-item label="年龄" prop="studentAge">
          <el-input v-model="form.studentAge" placeholder="请输入年龄"/>
        </el-form-item>
        <el-form-item label="爱好" prop="studentHobby">
          <el-input v-model="form.studentHobby" placeholder="请输入爱好"/>
        </el-form-item>
        <el-form-item label="性别" prop="studentSex">
          <el-select v-model="form.studentSex">
            <el-option
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :value="dict.value"
              :label="dict.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.studentStatus">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日" prop="studentBirthday">
          <el-date-picker clearable size="small"
           v-model="form.studentBirthday"
           type="date"
           value-format="yyyy-MM-dd"
           placeholder="选择生日">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <!--插槽的使用 -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>

    <!--学生信息导入对话框        关于el-upload参数名称的一些解释:
       limit:文件上传限制个数 需要监控文件上传进度，我们需要使用到这两个钩子on-progress,on-success.
       auto-upload: 是否在选取文件后立即上传 drag:是否启用拖拽上传-->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
         ref="upload"
         :limit = "1"
         accept=".xlsx, .xls"
         :headers="upload.headers"
         :action ="upload.url+ '?updateSupport=' +upload.updateSupport"
         :disabled = "upload.isUploading"
         :on-progress ="handleFileUploadProgress"
         :on-success = "handleFileSuccess"
         :auto-upload = "false"
         drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的学生数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listStudent,getStudent,delStudent,addStudent,updateStudent} from "@/api/system/student";
import {formateDate} from "@/api/tool/timeformatter";
import {getToken} from "@/utils/auth";
export default {
  name: "student",
  dicts:['sys_normal_disable','sys_user_sex'],
  components:{
  },
  data(){
    return {
      //遮罩层
      loading: true,
      //选中数组
      ids:[],
      //非单个禁用
      single: true,
      //非多个禁用
      multiple:true,
      //显示搜索条件
      showSearch: true,
      //总条数:
      total: 0,
      //学生信息表格数据
      studentList:[],
      //弹出层标题
      title:"",
      //是否显示弹出层
      open: false,
      //查询参数
      queryParams:{
        pageNum: 1,
        pageSize: 10,
        studentName: null,
        studentAge: null,
        studentHobby: null,
        studentSex: null,
        studentStatus: null,
        studentBirthday: null
      },
      //表单参数
      form:{},
      //学生导入参数
      upload:{
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/student/importData"
      },
      //表单校验
      rules:{

      }
    };
  },
  created(){
     this.getList();

  },
  methods:{
    /** 查询学生信息列表 */
    getList(){
      this.loading = true;
      listStudent(this.queryParams).then(response => {
        this.studentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //取消按钮 针对于弹出层
    cancel(){
      this.open = false;
      this.reset();
    },
    //表单重置
    reset(){
      this.form = {
        studentId: null,
        studentName: null,
        studentAge: null,
        studentHobby: null,
        studentSex: null,
        studentStatus: "0",
        studentBirthday: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery(){
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery(){
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据 比较死的写法
    handleSelectionChange(selection){
      this.ids = selection.map(item => item.studentId)
      this.single = selection.length !==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学生信息";
    },
    /**修改按钮操作 */
    handleUpdate(row){
      this.reset();
      const studentId = row.studentId || this.ids
      getStudent(studentId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title= "修改学生信息";
      });
    },
    /**提交按钮 注意使用$model去调用全局组件的方法 */
    submitForm(){
      this.$refs["form"].validate(valid =>{
        if(valid){
          if (this.form.studentId!= null){
            updateStudent(this.form).then(response =>{
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }else {
            addStudent(this.form).then(response =>{
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /**删除按钮操作 */
    handleDelete(row){
      const studentIds = row.studentId || this.ids;
      this.$confirm('是否确认删除编号为"' + studentIds+'"的数据项?',"警告",{
        confirmButtonText:"确定",
        cancelButtonText: "取消",
        type:"warning"
      }).then(function (){
        return delStudent(studentIds);
      }).then(()=>{
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /**导入按钮操作 */
    handleImport() {
      this.upload.title = "学生导入";
      this.upload.open = true;
    },
    /**下载模板的操作 */
    importTemplate() {
      this.download('system/student/importTemplate',
        {},`student_template_${formateDate(new Date())}.xlsx`)
    },
    /** 文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    //文件上传成功处理
    //对alert其中参数的一些解释；
    // overflow:控制文本溢出 auto：隐藏溢出内容,出现滚动条
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>"+response.msg +"</div>","导入结果",{dangerouslyUseHTMLString:true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /**导出按钮操作 */
    handleExport(){
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有学生信息数据项?',"警告",{
        confirmButtonText:"确定",
        cancelButtonText :"取消",
        type:"warning"
      }).then(()=> {
        this.download('system/student/export', {
          ...this.queryParams
        }, `student_${formateDate(new Date())}.xlsx`)
      })
    }
  }
};
</script>

